package ua.net.gm.common.entity;

import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;

/**
 *
 * @author Yason
 * @param <IdType>
 */
public abstract class EntityDict<IdType extends EntityId> implements IEntityDict<IdType>
{
    private BidiMap dict;

    private BidiMap getDict()
    {
        if (dict == null)
        {
            dict = new DualHashBidiMap();
        }
        return dict;
    }

    protected abstract IdType createId();

    @Override
    public IdType addEntity(String name)
    {
       return addEntity(new EntityName(name));
    }
    
    @Override
    public IdType addEntity(EntityName name)
    {
        if (getDict().containsValue(name))
        {
            throw new IllegalArgumentException("Entity dict already contains value : " + name);
        }
        return addOrReplaceEntity(name);
    }
    
    @Override
    public IdType addOrReplaceEntity(EntityName name)
    {
        IdType id = createId();
        getDict().put(id, name);
        return id;
    }
    
    @Override
    public IdType addNextEntity()
    {
        IdType id = createId();
        getDict().put(id, new EntityName(id.toString()));
        return id;
    }
    
    @Override
    public EntityName getName(IdType id)
    {
        return (EntityName) getDict().get(id);
    }

    @Override
    public IdType getId(EntityName name)
    {
        return (IdType) getDict().getKey(name);
    }

    @Override
    public IdType getId(String name)
    {
        return getId(new EntityName(name));
    }
}
